import fs from 'node:fs'
import path from 'node:path';
import { BrowserWindow } from 'electron';
import { Resource } from '@type/WindowService';
import { mkdir, writeNewFile, readFile } from '@e/methods/file';

/**
 * 写入资源
 */
export async function writeResource(rootPath: string, resources: Resource[], win: BrowserWindow) {
	for (let i = 0; i < resources.length; i++) {
		const item = resources[i];
		const curPath = path.join(rootPath, item.name);

		try {
			if (item.type === 'dir') {
				// 创建文件夹
				await mkdir(curPath);
				// 递归
				await writeResource(curPath, item.children, win);
			} else {
				// 写入文件
				await writeNewFile(win, curPath, item.data);
			}
		} catch (error) {
			// 出现错误则跳过
			continue;
		}
	}
}

/**
 * 读取资源
 * @param readPath 读取路径
 * @param isRoot 是否加入根路径
 * @param win 窗口对象
 */
export async function readResource(readPath: string, isRoot = true) {
  const resources: Resource[] = [];
  
  if (fs.existsSync(readPath)) {
		const files = fs.readdirSync(readPath)
    
    for (let i = 0; i < files.length; i++) {
      const curPath = path.join(readPath, files[i]);
			if (fs.statSync(curPath).isDirectory()) {
				// 递归删除
        const resource = await readResource(curPath, false);
        
        resources.push({
          type: 'dir',
          name: files[i],
          children: resource,
        })
			} else {
        // 读取文件
        const data = await readFile(curPath);

        resources.push({
          type: 'file',
          name: files[i],
          data: data.data,
        })
			}
    }
	}

	if (isRoot) {
		return [
			{
				type: 'dir',
				name: path.basename(readPath),
				children: resources,
			},
		] as Resource[];
	} else {
		return resources;
	}
}
